package com.opdar.athena.web.controllers;

import com.opdar.athena.base.Constants;
import com.opdar.athena.base.RedisSessionManager;
import com.opdar.athena.entities.TokenEntity;
import com.opdar.athena.entities.UserEntity;
import com.opdar.athena.web.service.UserService;
import com.opdar.platform.annotations.Request;
import com.opdar.platform.core.base.Context;
import com.opdar.platform.core.session.ISessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.Cookie;
import java.util.List;
import java.util.UUID;

/**
 * Created by shiju on 2017/1/23.
 */
@Controller
public class IndexController  {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService userService;
    @Autowired
    private RedisSessionManager sessionManager;

    @Request(value = "/login.html", format = Request.Format.VIEW)
    public Object login(String userName,String userPwd,String remember,Integer platform) {
        String token = (String) Context.getRequest().getSession().getAttribute("token");
        for(Cookie cookie:Context.getRequest().getCookies()){
            if(cookie.getName().equals("token")){
                token = cookie.getValue();
                if(!sessionManager.exist(token)){
                    token = null;
                }else{
                    Context.getRequest().getSession().setAttribute("token",token);
                }
                break;
            }
        }
        if(platform == null)platform = 0;
        long timeout = Constants.SESSION_TIMEOUT;
        if(token == null){
            String error = "";
            logger.info("登陆中.");
            if(userName!=null && userPwd != null){
                logger.info("认证中.");
                UserEntity user = userService.auth(userName, userPwd);
                if(user == null){
                    error = "用户名或密码错误";
                }else{
                    List<TokenEntity> tokens = sessionManager.getTokenWithUserId(user.getId());
                    if(tokens!=null && tokens.size() > 0){
                        for(TokenEntity tokenEntity:tokens){
                            if(tokenEntity.getPlatform() == 0){
                                token = tokenEntity.getToken();
                                if(sessionManager.exist(token)){
                                    sessionManager.remove(token);
                                }
                                sessionManager.removeToken(token,user.getId());
                                token = setUser(platform, timeout, user);
                            }
                        }
                    }
                    if(token == null){
                        token = setUser(platform, timeout, user);
                    }
                    Context.getRequest().getSession().setAttribute("token",token);
                    if(remember != null && remember.equals("on")){
                        //开启Cookie
                        Cookie cookie = new Cookie("token",token);
                        cookie.setMaxAge(7*60*60*24);
                        Context.getResponse().addCookie(cookie);
                    }
                    logger.info("用户[{}]认证通过.",user.getEmail());
                    return "redirect:/dashboard/index.html";
                }
            }
            Context.putAttribute("error",error);
            return "login/index";
        }
        if(!sessionManager.exist(token)){
            Context.getRequest().getSession().removeAttribute("token");
            Context.putAttribute("error","");
            return "login/index";
        }
        return "redirect:/dashboard/index.html";
    }

    private String setUser(Integer platform, long timeout, UserEntity user) {
        String token;
        token = UUID.randomUUID().toString();
        user.setPlatform(platform);
        sessionManager.set(token,user, timeout);
        return token;
    }

    @Request(value = "/logout.html", format = Request.Format.VIEW)
    public String logout(){
        String token = (String) Context.getRequest().getSession().getAttribute("token");
        if(token != null){
            sessionManager.remove(token);
            Context.getRequest().getSession().removeAttribute("token");
        }
        return "redirect:/login.html";
    }
}